<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\CourseList;
use app\common\model\ExperienceCourseList;
use app\common\model\TuanCourseList;
use app\common\model\GroupWork;
use app\common\model\User;
use think\Db;
/**
 * 订单列管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                if($row['type'] == 0){
                    $row['kecheng_name'] = CourseList::where('id',$row['kecheng_id'])->value('name');
                    $row['class'] = CourseList::where('id',$row['kecheng_id'])->value('class');
                }elseif($row['type'] == 1){
                    $row['kecheng_name'] = TuanCourseList::where('id',$row['kecheng_id'])->value('name');
                    $row['class'] = TuanCourseList::where('id',$row['kecheng_id'])->value('class');
                }elseif($row['type'] == 2){
                    $row['kecheng_name'] = ExperienceCourseList::where('id',$row['kecheng_id'])->value('name');
                    $row['class'] = ExperienceCourseList::where('id',$row['kecheng_id'])->value('class');
                }
                if($row['share_id']){
                    $row['share_name'] = User::where('id',$row['share_id'])->value('username');
                }else{
                    $row['share_name'] = '无';
                }
                $row->visible(['id','order_sn','userid','price','status','type','createtime','kecheng_name','apply_refund','share_name','share_id','class']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['username','mobile','avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function refund($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status'] != 1){
            $this->error('该订单不能退款');
        }
        if($row['type'] == 1){
            //如果是团购订单申请退款
            $group_work = GroupWork::where('id',$row['group_work_id'])->find();
            //查找拼团信息
            if($group_work){
                $res = false;
                if($group_work['status'] == 0 || $group_work['status'] == 3){
                    $this->error('该拼团信息有误');
                }
                //如果该团已经拼成，那就直接退款
                if($group_work['status'] == 2){
                    Db::startTrans();
                    try {
                        if($row['price']<0.01){
                            $result = [
                                'result_code'=>'SUCCESS'
                            ];
                        }else{
                            $money = $row['price']*100;
                            $result = refund_order($row['order_sn'], $money,$money);
                        }
                        if($result){
                            //$result = json_decode($result,true);
                            if($result['result_code'] == 'SUCCESS'){
                                $res = $this->model->where(['id'=>$row['id']])->update(['status'=>'2']);
                            }else{
                                Db::commit();
                                $this->error($result['err_code_des']);
                            }
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        $this->error($e->getMessage());
                        Db::rollback();
                        return false;
                    }
                }elseif($group_work['status'] == 1){
                    //如果是正在聘的团，把该团人数减1
                    //查询当前团下的订单
                    $tuan_order_count = $this->model->where('group_work_id',$row['group_work_id'])->where('status',1)->count();
                    if($tuan_order_count == 1){
                        //如果该团下只有一个人，那么退款后把该团直接改为拼团失败
                        Db::startTrans();
                        try {
                            if($row['price']<0.01){
                                $result = [
                                    'result_code'=>'SUCCESS'
                                ];
                            }else{
                                $money = $row['price']*100;
                                $result = refund_order($row['order_sn'], $money,$money);
                            }
                            if($result){
                                //$result = json_decode($result,true);
                                if($result['result_code'] == 'SUCCESS'){
                                    $res = $this->model->where(['id'=>$row['id']])->update(['status'=>'2']);
                                    if($res){
                                        $res1 = GroupWork::where('id',$row['group_work_id'])->update(['status'=>3]);
                                    }
                                }else{
                                    Db::commit();
                                    $this->error($result['err_code_des']);
                                }
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            $this->error($e->getMessage());
                            Db::rollback();
                            return false;
                        }
                    }else{
                        //如果申请退款的人是团长，那就把团长下面的那个人设为团长
                        Db::startTrans();
                        try {
                            if($row['price']<0.01){
                                $result = [
                                    'result_code'=>'SUCCESS'
                                ];
                            }else{
                                $money = $row['price']*100;
                                $result = refund_order($row['order_sn'], $money,$money);
                            }
                            if($result){
                                //$result = json_decode($result,true);
                                if($result['result_code'] == 'SUCCESS'){
                                    $res = $this->model->where(['id'=>$row['id']])->update(['status'=>'2']);
                                    if($res){
                                        $res1 = GroupWork::where('id',$row['group_work_id'])->setDec('num',1);
                                        if($group_work['userid'] == $row['userid'] && $res1){
                                            $tuan_order_info =  $this->model->where('group_work_id',$row['group_work_id'])->where('userid','<>',$row['userid'])->where('status',1)->order('id asc')->find();
                                            if($tuan_order_info){
                                                $res2 =  GroupWork::where('id',$row['group_work_id'])->update(['userid'=>$tuan_order_info['userid']]);
                                            }
                                        }

                                    }
                                }else{
                                    Db::commit();
                                    $this->error($result['err_code_des']);
                                }
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            $this->error($e->getMessage());
                            Db::rollback();
                            return false;
                        }
                    }
                }
                if($res){
                    $this->success('退款成功');
                }
            }
        }else{
            //如果是普通订单或者体验订单
            $res = false;
            //如果该团已经拼成，那就直接退款
            Db::startTrans();
            try {
                if($row['price']<0.01){
                    $result = [
                        'result_code'=>'SUCCESS'
                    ];
                }else{
                    $money = $row['price']*100;
                    $result = refund_order($row['order_sn'], $money,$money);
                }
                if($result){
                    //$result = json_decode($result,true);
                    if($result['result_code'] == 'SUCCESS'){
                        $res = $this->model->where(['id'=>$row['id']])->update(['status'=>'2']);
                    }
                    else{
                        Db::commit();
                        $this->error($result['err_code_des']);
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $this->success('退款成功');
            }
        }
    }
}
